<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xizhongren8980/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xizhongren8980/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xizhongren8980/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xizhongren8980/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xizhongren8980/css/main.css">


<link rel="stylesheet" href="/xizhongren8980/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xizhongren8980/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="在上一篇笔记中已经对 mybatis 开发 Dao 层有了一个最基本的认识，这篇笔记主要记录一下通过 mybatis  的 mapper 代理方法实现与数据库的基本的增删改查操作。">
<meta property="og:type" content="article">
<meta property="og:title" content="【MyBatis入门_02】之增删改查操作">
<meta property="og:url" content="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/06/06/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E6%93%8D%E4%BD%9C/index.html">
<meta property="og:site_name" content="一杯茶一包烟，一个BUG改一天">
<meta property="og:description" content="在上一篇笔记中已经对 mybatis 开发 Dao 层有了一个最基本的认识，这篇笔记主要记录一下通过 mybatis  的 mapper 代理方法实现与数据库的基本的增删改查操作。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605191623.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606081707.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606093419.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605193656.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605194122.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605235419.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606000733.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606084128.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606084207.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606092816.png">
<meta property="article:published_time" content="2020-06-06T01:34:56.493Z">
<meta property="article:modified_time" content="2020-06-10T05:07:49.179Z">
<meta property="article:author" content="MisterTian">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="框架">
<meta property="article:tag" content="mybatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605191623.png">

<link rel="canonical" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/06/06/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E6%93%8D%E4%BD%9C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【MyBatis入门_02】之增删改查操作 | 一杯茶一包烟，一个BUG改一天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xizhongren8980/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一杯茶一包烟，一个BUG改一天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">收藏永不停止，学习永不开始</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xizhongren8980/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/xizhongren8980/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xizhongren8980/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xizhongren8980/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xizhongren8980/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/06/06/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E6%93%8D%E4%BD%9C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xizhongren8980/images/head.jpg">
      <meta itemprop="name" content="MisterTian">
      <meta itemprop="description" content="一个小菜鸟">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一杯茶一包烟，一个BUG改一天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【MyBatis入门_02】之增删改查操作
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-06-06 09:34:56" itemprop="dateCreated datePublished" datetime="2020-06-06T09:34:56+08:00">2020-06-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-10 13:07:49" itemprop="dateModified" datetime="2020-06-10T13:07:49+08:00">2020-06-10</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/xizhongren8980/categories/MyBatis/" itemprop="url" rel="index"><span itemprop="name">MyBatis</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在上一篇笔记中已经对 mybatis 开发 Dao 层有了一个最基本的认识，这篇笔记主要记录一下通过 mybatis  的 mapper 代理方法实现与数据库的基本的增删改查操作。<a id="more"></a></p>
<p>在使用 mapper 代理的方法开发 dao 时，我们只需要在 mybatis 环境搭好的基础上做两件事：</p>
<ul>
<li>编写相应的 dao 接口 （ 例如 BookDao）</li>
<li>编写对应 dao 接口的映射文件（BookDao.xml）</li>
</ul>
<p>接下来以向数据库 t_book 表为例，分别进行增删改查操作。</p>
<h3 id="向数据库表插入记录"><a href="#向数据库表插入记录" class="headerlink" title="向数据库表插入记录"></a>向数据库表插入记录</h3><h4 id="编写-dao-接口层方法-saveBook-Book-book"><a href="#编写-dao-接口层方法-saveBook-Book-book" class="headerlink" title="编写 dao 接口层方法 saveBook(Book book)"></a>编写 dao 接口层方法 <code>saveBook(Book book)</code></h4><p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605191623.png" alt="image-20200605191612305"></p>
<h4 id="配置-BookDao-xml-映射文件"><a href="#配置-BookDao-xml-映射文件" class="headerlink" title="配置 BookDao.xml 映射文件"></a>配置 BookDao.xml 映射文件</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--插入新增书籍</span></span><br><span class="line"><span class="comment">	id 就是表示我们要执行的方法，parameterType 表示我们的传参类型，如果方法没有参数则不写</span></span><br><span class="line"><span class="comment">--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">"saveBook"</span> <span class="attr">parameterType</span>=<span class="string">"com.xizhongren.domain.Book"</span>&gt;</span></span><br><span class="line">        insert into t_book(name, price, author) values(#&#123;name&#125;,#&#123;price&#125;,#&#123;author&#125;);</span><br><span class="line">    <span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>由于我的Book类的属性名称和数据库表中的字段完全相同，因此可以直接按照上面这种写法编写，如果不同的话，还需要另外进行属性的映射配置。</p>
<h4 id="编写测试类"><a href="#编写测试类" class="headerlink" title="编写测试类"></a>编写测试类</h4><p>首先是抽取出测试代码的相同部分，这样在测试其他方法时就省事多了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Before</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="comment">//1.读取配置文件</span></span><br><span class="line">    inputStream = Resources.getResourceAsStream(<span class="string">"SqlMapConfig.xml"</span>);</span><br><span class="line">    <span class="comment">//2.创建SqlSessionFactory工厂</span></span><br><span class="line">    SqlSessionFactoryBuilder builder = <span class="keyword">new</span> SqlSessionFactoryBuilder();</span><br><span class="line">    SqlSessionFactory factory = builder.build(inputStream);</span><br><span class="line">    <span class="comment">//3.使用工厂生产SqlSession对象</span></span><br><span class="line">    session = factory.openSession();</span><br><span class="line">    <span class="comment">//4.使用SqlSession创建Dao接口的代理对象</span></span><br><span class="line">    bookDao = session.getMapper(BookDao<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@After</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="comment">//手动提交事物</span></span><br><span class="line">    session.commit();</span><br><span class="line">    <span class="comment">//6.释放资源</span></span><br><span class="line">    session.close();</span><br><span class="line">    inputStream.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>编写测试方法 <code>testSaveBook()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSaveBook</span><span class="params">()</span> </span>&#123;</span><br><span class="line"><span class="comment">// 由于id值是自增的，所以传参null即可</span></span><br><span class="line">Book book = <span class="keyword">new</span> Book(<span class="keyword">null</span>,<span class="string">"钢铁是怎样炼成的"</span>,<span class="keyword">new</span> BigDecimal(<span class="number">188</span>),<span class="string">"奥斯特洛夫斯基"</span>);</span><br><span class="line">bookDao.saveBook(book);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行成功</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606081707.png" alt="image-20200605193013553"></p>
<p>再执行查询所有图书方法验证结果</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606093419.png" alt="image-20200605193121624"></p>
<p>让人意想不到的是数据库中并未插入新的数据。这是为什么呢，明明执行没报错的。</p>
<p>现在我们再仔细看看执行保存方法后的输出</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605193656.png" alt="image-20200605193654199"></p>
<p>原来是默认关闭了自动提交事务，导致事务回滚了。</p>
<p>因此解决办法就是我们进行手动提交事务。在 testSaveBook() 方法后面添加一行代码即可。为了方便，也可以把这一行代码抽取到@After 代码块中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">session.commit();<span class="comment">//提交事务</span></span><br></pre></td></tr></table></figure>

<p>可以看到，现在已经成功在数据库表中插入一条新数据。尽管插入多次都没提交事务，但是id值还是会被分配占用的，所以这里看到的id就是9，而不是5。</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605194122.png" alt="image-20200605194119895"></p>
<h3 id="更新和删除数据库表记录"><a href="#更新和删除数据库表记录" class="headerlink" title="更新和删除数据库表记录"></a>更新和删除数据库表记录</h3><h4 id="编写-dao-层方法"><a href="#编写-dao-层方法" class="headerlink" title="编写 dao 层方法"></a>编写 dao 层方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**更新图书</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> [book]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">updateBook</span><span class="params">(Book book)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**通过id值删除图书</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> [id]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">deleteBook</span><span class="params">(Integer id)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="配置-BookDao-xml-映射文件-1"><a href="#配置-BookDao-xml-映射文件-1" class="headerlink" title="配置 BookDao.xml 映射文件"></a>配置 BookDao.xml 映射文件</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">&lt;!--更新图书--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateBook"</span> <span class="attr">parameterType</span>=<span class="string">"com.xizhongren.dao.BookDao"</span>&gt;</span></span><br><span class="line">        update t_book set name=#&#123;name&#125;,price=#&#123;price&#125;,author=#&#123;author&#125; where id=#&#123;id&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--根据id删除图书--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">"deleteBook"</span> <span class="attr">parameterType</span>=<span class="string">"int"</span>&gt;</span></span><br><span class="line">        delete from t_book where id=#&#123;id&#125;;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>由于需要传参，这里也是需要 parameterType 属性的。另外，在对于诸如int等基本类型及其包装类的参数，parameterType 属性值可以写<code>java.lang.Integer</code>这样的标准写法，也可以直接写<code>int</code> 。</p>
<h4 id="编写测试类-1"><a href="#编写测试类-1" class="headerlink" title="编写测试类"></a>编写测试类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testUpdateBook</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       Book book = <span class="keyword">new</span> Book(<span class="number">1</span>, <span class="string">"数据库从入门到删库"</span>, <span class="keyword">new</span> BigDecimal(<span class="number">99</span>), <span class="string">"戏中人"</span>);</span><br><span class="line">       bookDao.updateBook(book);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testDeleteBook</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="keyword">int</span> id = <span class="number">4</span>;</span><br><span class="line">       bookDao.deleteBook(id);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h4 id="查看测试结果"><a href="#查看测试结果" class="headerlink" title="查看测试结果"></a>查看测试结果</h4><p>更新</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200605235419.png" alt="image-20200605235417021"></p>
<p>删除</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606000733.png" alt="image-20200606000730572"></p>
<h3 id="查询一个和模糊查询"><a href="#查询一个和模糊查询" class="headerlink" title="查询一个和模糊查询"></a>查询一个和模糊查询</h3><h4 id="编辑dao接口层方法"><a href="#编辑dao接口层方法" class="headerlink" title="编辑dao接口层方法"></a>编辑dao接口层方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**通过id值查询图书</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> [id]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">Book <span class="title">selectBookById</span><span class="params">(Integer id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**通过书名查询图书</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> [name]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">List&lt;Book&gt; <span class="title">selectBookByName</span><span class="params">(String name)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="编写映射文件"><a href="#编写映射文件" class="headerlink" title="编写映射文件"></a>编写映射文件</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--通过id值查询图书--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectBookById"</span> <span class="attr">parameterType</span>=<span class="string">"int"</span> <span class="attr">resultType</span>=<span class="string">"com.xizhongren.domain.Book"</span>&gt;</span></span><br><span class="line">       select * from t_book where id=#&#123;id&#125;</span><br><span class="line">   <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">&lt;!--通过书名查询图书--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectBookByName"</span> <span class="attr">parameterType</span>=<span class="string">"string"</span> <span class="attr">resultType</span>=<span class="string">"com.xizhongren.domain.Book"</span>&gt;</span></span><br><span class="line">       select * from t_book where name like #&#123;name&#125;</span><br><span class="line">   <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="编写测试方法"><a href="#编写测试方法" class="headerlink" title="编写测试方法"></a>编写测试方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSelectBookById</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="keyword">int</span> id = <span class="number">2</span>;</span><br><span class="line">       Book book = bookDao.selectBookById(id);</span><br><span class="line">       System.out.println(book);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSelectBookByName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       List&lt;Book&gt; book = bookDao.selectBookByName(<span class="string">"%数据%"</span>);</span><br><span class="line">       <span class="keyword">for</span> (Book book1 : book) &#123;</span><br><span class="line">           System.out.println(book1);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h4 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h4><p>通过id值查询</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606084128.png" alt="image-20200606084122395"></p>
<p>通过名称模糊查询</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606084207.png" alt="image-20200606084205676"></p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><ul>
<li><p>在 SqlMapConfig.xml 中配置数据库连接池，通过连接池来管理数据库链接，可以避免由于频繁创建数据库链接、释放造成资源浪费而影响系统性能。</p>
</li>
<li><p>将 Sql 语句配置在映射文件中，与 java 代码分离了，维护起来相对容易一些。</p>
</li>
<li><p>mybatis 会自动将 java 对象映射至 sql  语句，通过 statement 中的 parameterType 定义输入参数的类型，以及将 sql 执行结果映射至 java 对象，由 resultType 定义返回数据类型。</p>
</li>
<li><p>在 parameterType 属性中，基本类型和 String 类型我们可以直接写类型名称或者使用包名、类名的方法，而对于实体类型，目前只能使用全限定类名，其原因在于 mybatis 在加载时已经把常用的数据类型注册了别名，从而我们在使用时可以不写包名，而我们自定义的实体类并没有注册别名，所以必须使用全限定类名。</p>
<p>下图是mybatis支持的默认别名</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200606092816.png" alt="image-20200606092813920"></p>
</li>
</ul>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xizhongren8980/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"># 数据库</a>
              <a href="/xizhongren8980/tags/%E6%A1%86%E6%9E%B6/" rel="tag"># 框架</a>
              <a href="/xizhongren8980/tags/mybatis/" rel="tag"># mybatis</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/06/04/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%88%9D%E8%AF%86MyBatis/" rel="prev" title="【MyBatis入门_01】之初识MyBatis">
      <i class="fa fa-chevron-left"></i> 【MyBatis入门_01】之初识MyBatis
    </a></div>
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/06/06/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BD%93%E7%B1%BB%E5%8C%85%E8%A3%85%E5%AF%B9%E8%B1%A1%E4%BD%9C%E4%B8%BA%E6%9F%A5%E8%AF%A2%E6%9D%A1%E4%BB%B6/" rel="next" title="【MyBatis入门_03】之使用实体类包装对象作为查询条件">
      【MyBatis入门_03】之使用实体类包装对象作为查询条件 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#向数据库表插入记录"><span class="nav-number">1.</span> <span class="nav-text">向数据库表插入记录</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#编写-dao-接口层方法-saveBook-Book-book"><span class="nav-number">1.1.</span> <span class="nav-text">编写 dao 接口层方法 saveBook(Book book)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置-BookDao-xml-映射文件"><span class="nav-number">1.2.</span> <span class="nav-text">配置 BookDao.xml 映射文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编写测试类"><span class="nav-number">1.3.</span> <span class="nav-text">编写测试类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更新和删除数据库表记录"><span class="nav-number">2.</span> <span class="nav-text">更新和删除数据库表记录</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#编写-dao-层方法"><span class="nav-number">2.1.</span> <span class="nav-text">编写 dao 层方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置-BookDao-xml-映射文件-1"><span class="nav-number">2.2.</span> <span class="nav-text">配置 BookDao.xml 映射文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编写测试类-1"><span class="nav-number">2.3.</span> <span class="nav-text">编写测试类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#查看测试结果"><span class="nav-number">2.4.</span> <span class="nav-text">查看测试结果</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询一个和模糊查询"><span class="nav-number">3.</span> <span class="nav-text">查询一个和模糊查询</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#编辑dao接口层方法"><span class="nav-number">3.1.</span> <span class="nav-text">编辑dao接口层方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编写映射文件"><span class="nav-number">3.2.</span> <span class="nav-text">编写映射文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编写测试方法"><span class="nav-number">3.3.</span> <span class="nav-text">编写测试方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#运行结果"><span class="nav-number">3.4.</span> <span class="nav-text">运行结果</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小结"><span class="nav-number">4.</span> <span class="nav-text">小结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="MisterTian"
      src="/xizhongren8980/images/head.jpg">
  <p class="site-author-name" itemprop="name">MisterTian</p>
  <div class="site-description" itemprop="description">一个小菜鸟</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xizhongren8980/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/xizhongren8980/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/xizhongren8980/tags/">
          
        <span class="site-state-item-count">101</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://mistertian8980.github.io/" title="https:&#x2F;&#x2F;mistertian8980.github.io&#x2F;" rel="noopener" target="_blank">Github博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MisterTian</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/xizhongren8980/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/xizhongren8980/lib/anime.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.ui.min.js"></script>

<script src="/xizhongren8980/js/utils.js"></script>

<script src="/xizhongren8980/js/motion.js"></script>


<script src="/xizhongren8980/js/schemes/pisces.js"></script>


<script src="/xizhongren8980/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_lines.min.js"></script>


  




  
<script src="/xizhongren8980/js/local-search.js"></script>













  

  

</body>
</html>
